package com.zahb.qadx.ui.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.zahb.qadx.R;
import com.zahb.qadx.base.BaseActivity;
import com.zahb.qadx.base.BaseApplication;
import com.zahb.qadx.model.ExercisesSpecial;
import com.zahb.qadx.net.RetrofitService;
import com.zahb.qadx.ui.activity.topic.SpecialPracticeActivity;
import com.zahb.qadx.util.Constant;
import com.zahb.qadx.util.DisplayUtil;
import com.zahb.qadx.util.PackageUtils;
import com.zahb.qadx.util.Tips;
import com.zahb.qadx.util.WebViewHelper;
import com.zahb.qadx.webview.MyWebViewActivity;

import org.jetbrains.annotations.NotNull;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import io.reactivex.android.schedulers.AndroidSchedulers;

/**
 * 答题练习-专项练习
 */
public class AnswerExercisesSpecialActivity extends BaseActivity implements OnItemChildClickListener {

    private BaseQuickAdapter<ExercisesSpecial, BaseViewHolder> mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }


    @Override
    protected int getLayout() {
        return R.layout.activity_answer_exercises_special;
    }

    @Override
    protected void onStart() {
        super.onStart();
        getSpecialPracticeList();//网络请求刷新数据
    }

    @Override
    protected void initViews() {
        RecyclerView recyclerView = findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        recyclerView.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) {
                outRect.set(0, 0, 0, DisplayUtil.dip2px(16f));
            }
        });
        mAdapter = new BaseQuickAdapter<ExercisesSpecial, BaseViewHolder>(R.layout.item_list_exercises_special) {
            @Override
            protected void convert(@NotNull BaseViewHolder baseViewHolder, ExercisesSpecial item) {
                baseViewHolder.setText(R.id.tv_name, item.getQuesLibName())
                        .setText(R.id.tv_count, new StringBuilder("题目数量：").append(item.getQuestionCount()))
                        .setText(R.id.tv_percent, new StringBuilder("正确率：").append(item.getAccuracy()))
                        .setVisible(R.id.tv_percent, item.getQuesLibStatus() != 0)
                        .setText(R.id.tv_button1, item.getQuesLibStatus() != 0 ? "继续练习" : "开始练习")
                        .setText(R.id.tv_button2, "重新练习")
                        .setVisible(R.id.tv_button2, item.getQuesLibStatus() != 0);
            }
        };
        View emptyView = View.inflate(getContext(), R.layout.empty_layout, null);
        emptyView.setVisibility(View.VISIBLE);
        mAdapter.setEmptyView(emptyView);
        mAdapter.addChildClickViewIds(R.id.tv_button1, R.id.tv_button2);
        mAdapter.setOnItemChildClickListener(this);
        recyclerView.setAdapter(mAdapter);
    }

    @Override
    protected int getTitleStringRes() {
        return R.string.answer_exercises;
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        if (view.getId() == R.id.tv_button1) {// 开始练习/继续练习
            toSpecialH5Page(mAdapter.getItem(position));
        } else if (view.getId() == R.id.tv_button2) {// 重新练习
            studentSpecialPracticeRestart(mAdapter.getItem(position));
        }
    }

    private void getSpecialPracticeList() {
        showProgressDialog("");
        addDisposable(RetrofitService.getNetService().getSpecialPracticeList()
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    hideProgressDialog();
                    if (response.getStatusCode() == Constant.CODE_SUCCESS) {
                        mAdapter.setList(response.getData());
                    } else {
                        showBindToast(response.getErrorInfo());
                    }
                }, throwable -> {
                    hideProgressDialog();
                    throwable.printStackTrace();
                    Tips.RequestError(getActivity());
                }));
    }

    private void toSpecialH5Page(ExercisesSpecial data) {
        try {
            String baseUrl = "http://192.168.1.114/";
//            String token = URLEncoder.encode(BaseApplication.getContext().getToken(), "UTF-8");


            String token = URLEncoder.encode(BaseApplication.getContext().getToken(), "UTF-8");
            String url = WebViewHelper.getBaseUrl() + "propaganda/specialProjectQues?fromType=1&token=" + token +
                    "&id=" + data.getQuesLibId();
            Log.e("专项练习", url);
            SharedPreferences settingss = getActivity().getSharedPreferences("tryToSwitch", 0);
            int isAmazing = settingss.getInt("tryToSwitch", 0);
            if (isAmazing == 2) {
                //原生专项练习 梁尔宾
                Intent intent = new Intent(AnswerExercisesSpecialActivity.this, SpecialPracticeActivity.class);
                intent.putExtra("id", data.getQuesLibId());
                startActivity(intent);
            } else {
                MyWebViewActivity.actionStart(getContext(), url, "专项练习", 1);
            }

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }


    }

    private void studentSpecialPracticeRestart(ExercisesSpecial data) {
        showProgressDialog("");
        addDisposable(RetrofitService.getNetService()
                .studentSpecialPracticeRestart(data.getQuesLibId())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    hideProgressDialog();
                    if (response.getStatusCode() == Constant.CODE_SUCCESS) {
                        toSpecialH5Page(data);
                    } else {
                        showBindToast(response.getErrorInfo());
                    }
                }, throwable -> {
                    hideProgressDialog();
                    throwable.printStackTrace();
                    Tips.RequestError(getActivity());
                }));
    }
}
